package com.medication.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.medication.model.LimitMedication;
import com.medication.utils.ExcelExporter;
import com.medication.utils.HandlerExcelData;
import com.medication.utils.PinyinTool;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author  heem
 * @create time 创建时间：2017年3月30日 下午4:43:02 
 * @version 1.0 
 * @since  
*/
public class LimitMedicationService extends HandlerExcelData<LimitMedication>{

	@Override
	public String handlerData(List<List<Object>> objects) {
		if(objects!=null&& !objects.isEmpty()){
			List<LimitMedication> list = Lists.newArrayList();
			PinyinTool tool =new PinyinTool();
			for(List<Object> objs :objects){
				LimitMedication limit = new LimitMedication();
				limit.set("category", objs.get(0));
				limit.set("code", objs.get(1));
				limit.set("name", objs.get(2));
				limit.set("type", objs.get(3));
				limit.set("reagentType", objs.get(4));
				limit.set("limit", objs.get(5));
				limit.set("remark", objs.get(6));
				if(objs.get(1)!=null){
					limit.set("nameFirstEn", tool.getFirstSpell((String)objs.get(2)));
					try {
						limit.set("nameAllEn", tool.toPinYin((String)objs.get(2)));
					} catch (BadHanyuPinyinOutputFormatCombination e) {
						e.printStackTrace();
					}	
				}
				list.add(limit);
			}
			Db.update("delete from limit_medication");
			//每次执行100条
			Db.batchSave(list, 500);
		}
		return "成功导入"+objects.size()+"条数据，如果数据不对，请检查Excel数据是否有空行或者选了错误的文件";
	}

	@Override
	public File exportExcel(List<LimitMedication> datas) {
		List<String> heads = Lists.newArrayList();
		heads.add("类别");
		heads.add("项目代码");
		heads.add("中文名称");
		heads.add("分类");
		heads.add("剂型");
		heads.add("限制");
		heads.add("备注");
		// 导出结果excel
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String expPath = System.getProperty("java.io.tmpdir")+"限制性用药药品编码表"+sdf.format(new Date())+".xls";
		try {
			return ExcelExporter.generateExcelFile(expPath, datas, heads.toArray(new String[] {}));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
